package yoshop_ast

import (
	"bytes"
	"context"
	"io"
	"mime/multipart"
	"net/http"
)

// Client 萤火商城client
type Client struct {
	token    string
	endpoint string
}

// NewClient 创建萤火商城client
//
// token: 萤火商城管理端当前用户token，在请求的header中的access-token
//
// endpoint: 萤火商城API地址域名 格式为：http://xx.com
func NewClient(token, endpoint string) *Client {
	return &Client{
		token:    token,
		endpoint: endpoint,
	}
}

func (c *Client) doGet(ctx context.Context, gUrl string) ([]byte, error) {
	// 创建请求
	req, err := http.NewRequestWithContext(ctx, "GET", c.endpoint+gUrl, nil)
	if err != nil {
		return nil, err
	}

	// 设置 headers
	req.Header.Set("access-token", c.token)
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := &http.Client{}

	// proxyURL, _ := url.Parse("http://127.0.0.1:8888")
	// transport := &http.Transport{
	// 	Proxy: http.ProxyURL(proxyURL),
	// }
	// client.Transport = transport

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

func (c *Client) doPost(ctx context.Context, postUrl string, reqBody io.Reader) ([]byte, error) {
	// 创建请求
	req, err := http.NewRequestWithContext(ctx, "POST", c.endpoint+postUrl, reqBody)
	if err != nil {
		return nil, err
	}

	// 设置 headers
	req.Header.Set("access-token", c.token)
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")

	client := &http.Client{}

	// proxyURL, _ := url.Parse("http://127.0.0.1:8888")
	// transport := &http.Transport{
	// 	Proxy: http.ProxyURL(proxyURL),
	// }
	// client.Transport = transport

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

// doPostFile 处理文件上传请求
//
// fieldName: 表单中文件字段的名称
func (c *Client) doPostFile(ctx context.Context, postUrl string, file io.Reader, fieldName, fileName string, formData map[string]string) ([]byte, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	// 添加文件
	part, err := writer.CreateFormFile(fieldName, fileName)
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return nil, err
	}

	// 添加其他表单字段
	for key, val := range formData {
		_ = writer.WriteField(key, val)
	}

	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequestWithContext(ctx, "POST", c.endpoint+postUrl, body)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", writer.FormDataContentType())
	// 设置其他必要的header
	req.Header.Set("access-token", c.token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return io.ReadAll(resp.Body)
}
